<?php
namespace Admin\Controller;

class ApiController extends \Think\Controller{
    
    public $post_data; //微信服务器发送过来的数据
    public $rule;
    public $replyobj;
    public $resultStr;
    public $customer_id;
    
    public function index(){
        $token = C('TOKEN');
        if(isset($_GET['echostr']) && isset($_GET["signature"]) && isset($_GET["timestamp"]) && isset($_GET["nonce"])){
            echo $this->valid($token); //公众平台校验
        }else{
            if($customer_id = intval(I('get.customer_id'))){
                $this->customer_id = $customer_id;
            }else{
                $this->customer_id = 1;
            }
            echo $this->responseMsg();
        }
    }
    
    //解析微信post过来的数据
    private function getPostData(){
        $postObj = simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"], 'SimpleXMLElement', LIBXML_NOCDATA);
        if(trim($postObj->MsgType) != 'event')file_put_contents('aaa.txt',$GLOBALS["HTTP_RAW_POST_DATA"]);
        $data = array();
        //通用消息
        $data['FromUserName'] = trim($postObj->FromUserName);
        $data['ToUserName'] = trim($postObj->ToUserName);
        $data['FromMsgType'] = trim($postObj->MsgType);
        $data['Keyword'] = trim($postObj->Content);
        $data['CreateTime'] = trim($postObj->CreateTime);
        //图片消息
        $data['PicUrl'] = trim($postObj->PicUrl);
        //语音消息
        $data['Recognition']  = trim($postObj->Recognition);
        //地理位置消息
        $data['Location_X'] = trim($postObj->Location_X);
        $data['Location_Y'] = trim($postObj->Location_Y);
        $data['Label'] = trim($postObj->Label);
        //事件推送
        $data['Event'] = trim($postObj->Event);
        $data['EventKey'] = trim($postObj->EventKey);
        
        if($data['FromMsgType'] == 'image'){
            $data['Keyword'] = '[发送图片]';
        }elseif($data['FromMsgType'] == 'voice'){
            $data['Keyword'] = $data['Recognition'];
        }elseif($data['FromMsgType'] == 'location'){
            $data['Keyword'] = '[发送位置]'.$data['Label'];
        }elseif($data['Event'] == 'CLICK' || $data['Event'] == 'VIEW'){//菜单点击事件
            $data['Keyword'] = $data['EventKey'];
        }
        
        $data['timesign']=time().rand(1000,9999);
        return $data;
    }
    
    //回复微信
    private function responseMsg(){
        $this->post_data = $this->getPostData();//解析微信post过来的数据
		// file_put_contents('bbb.txt',json_encode($this->post_data));
        $this->addMessage();//收消息入库

        $Member = D('Member');
        //添加或更新会员
        $memberRow = $Member->where(array("fromuser"=>$this->post_data['FromUserName']))->find();
        
        $rowMem = array();
        $rowMem['customer_id']    = $this->customer_id;
        $rowMem['fromuser']    = $this->post_data['FromUserName'];
        $rowMem['timesign']    = $this->post_data['timesign'];
        $rowMem['lng']    = $this->post_data['Location_Y'];
        $rowMem['lat']    = $this->post_data['Location_X'];
        
        if(strtolower($this->post_data['Event']) == 'unsubscribe'){
            $rowMem['unsubscribe_time'] = time();
            $rowMem['status'] = '0';
        }else{
            //非取消关注时获取用户头像昵称等信息
            if($this->post_data['FromUserName'] ){//&& empty($memberRow['nickname'])
                $access_token = D('Customer')->getToken($this->customer_id);//获取access_token
                $userInfo = D('Api')->getUserInfo($access_token,$this->post_data['FromUserName']);//获取用户基本信息
                if(!empty($userInfo['nickname'])){
                    $rowMem['status'] = $userInfo['subscribe'];
                    $rowMem['group_id'] = $userInfo['groupid'];
                    $rowMem['nickname'] = $userInfo['nickname'];
                    $rowMem['headimgurl'] = $userInfo['headimgurl'];
                    $rowMem['sex'] = $userInfo['sex'];
                    $rowMem['language'] = $userInfo['language'];
                    $rowMem['country'] = $userInfo['country'];
                    $rowMem['province'] = $userInfo['province'];
                    $rowMem['city'] = $userInfo['city'];
                    if($userInfo['subscribe']=='1')$rowMem['subscribe_time'] = $userInfo['subscribe_time'];
                }
            }
        }
        empty($memberRow) ? $Member->add($rowMem) : $Member->where(array('id'=>$memberRow['id']))->save($rowMem);
        
        //关注+取消关注
        if(strtolower($this->post_data['Event'])=='subscribe' || strtolower($this->post_data['Event'])=='unsubscribe'){
            //插入关注记录
            $careStatus = strtolower($this->post_data['Event']) == 'subscribe' ? '1' : '0';
            D('CareRecord')->add(array('customer_id'=>$this->customer_id,'is_care'=>$careStatus,'fromuser'=>$this->post_data['FromUserName']));
            //关注自动回复
            $replyRow = D("AutoReply")->where(array('type'=>'1','state'=>'1'))->find();
            if($careStatus == '1' && $replyRow){
                if($replyRow['is_content'] == '1'){
                    return $this->create_xmlcontent('text', $replyRow['content']);
                }else{
                    $this->post_data['Keyword'] = $replyRow['keyword'];
                }
            }else{
                return false;
            }
        }
        
        if(strtolower($this->post_data['Event']) != 'location'){//暂不处理自动上传地理位置的信息
            $returnxml = $this->getInfo();
        }
        return $returnxml;
    }
    
    //获取回复内容
    public function getInfo(){
        if($this->post_data['FromMsgType'] == 'voice'){
           $this->post_data['Keyword'] = rtrim($this->post_data['Keyword'],'。！，？');
        }
        //根据发送的位置获取最近的5个网点信息
        if($this->post_data['FromMsgType'] == 'location'){
            if($data = $this->getWebsiteInfo()){
                return $this->create_xmlcontent($data['msgtype'], $data['content'], $data['title'], $data['description'], $data['picurl'], $data['url'], $data['bodystr']);
            }else{
                return $this->getAutoReply();
            }
        }
        //签到设置
        if($this->post_data['Event'] == 'CLICK'){
            $this->post_data['Keyword'] = $this->getSignKeyword();
        }
        $keywordinfo = D('Keyword')->where(array('keyword'=>$this->post_data['Keyword']))->find();
        if(empty($keywordinfo)){
            return $this->getAutoReply();
        }else{
            $common_info = D('Common')->where(array('id'=>$keywordinfo['common_id'],'state'=>'1'))->find();
            if(empty($common_info)){
                return $this->getAutoReply();
            }else{
                $data = array();
                switch($keywordinfo['type']){
                    case 'text':$data = $this->getText($keywordinfo['common_id']);break;
                    case 'image':$data = $this->getImage($keywordinfo['common_id']);break;
                    case 'single':$data = $this->getSingle($keywordinfo['common_id']);break;
                    case 'muti':$data = $this->getMuti($keywordinfo['common_id']);break;
                }
                if(empty($data)) return $this->getAutoReply();
                return $this->create_xmlcontent($data['msgtype'], $data['content'], $data['title'], $data['description'], $data['picurl'], $data['url'], $data['bodystr']);
            }
        }
    }
    
    //获取签到关键词
    public function getSignKeyword(){
        $post_keyword = $this->post_data['Keyword'];
        $sign_info = D('Sign')->where(array('customer_id'=>$this->customer_id))->find();
        if($post_keyword == $sign_info['keyword']){
            $signArticle = D('SignArticle');
            $Member = D('Member');
            $signLog = D('SignLog');
            $member_info = $Member->where(array('fromuser'=>$this->post_data['FromUserName']))->find();
            $last_time = $signLog->where(array('customer_id'=>$this->customer_id,'member_id'=>$member_info['id']))->order('sign_time desc')->getField('sign_time');
            file_put_contents('aaa.txt',$last_time);
            if(strtotime($last_time) < strtotime(date('Y-m-d'))){
            	$article_info = $this->getSignArticle($member_info['id'],true);
            	if(!empty($article_info)){
            		$Member->changeCent($member_info,$sign_info['cent'],'签到');//改变积分
            		$signLog->addLog($member_info,$sign_info['cent'],$article_info['common_id']);//添加签到日志
            		return $article_info['keyword'];
            	}else{
            		return $post_keyword;
            	}
            }else{
            	$today = date('Y-m-d');
            	$where = "customer_id='{$this->customer_id}' and member_id='{$member_info['id']}' and left(sign_time,10)='$today'";
            	$send_count = $signLog->where($where)->count();
            	
            	$article_info = $this->getSignArticle($member_info['id']);
            	if(empty($article_info)){
            		return $post_keyword;
            	}else{
            		if($send_count < $sign_info['total_num']){
            			$Member->changeCent($member_info,$sign_info['cent'],'签到');//改变积分
            			$signLog->addLog($member_info,$sign_info['cent'],$article_info['common_id']);//添加签到日志
                        return $article_info['keyword'];
            		}
                    return $post_keyword;
            	}
            }
        }else{
            return $post_keyword;
        }
    }
    //返回一条图文
    public function getSignArticle($member_id,$is_reset = false){
    	$signArticle = D('SignArticle');
    	$where = array('customer_id'=>$this->customer_id);
    	//查询所有图文
    	$article_info = $signArticle->where($where)->order("id asc")->select();
        //查询最后一条签到记录
        $where['member_id'] = $member_id;
        $lastSignLog = D('SignLog')->where($where)->order('sign_time desc')->find();
        
    	if(empty($lastSignLog) || $is_reset){
            return $article_info[0];
        }else{
            foreach($article_info as $key=>$val){
                if($val['common_id'] == $lastSignLog['common_id']){
                    if(empty($article_info[$key+1])){
                        return $article_info[0];
                    }else{
                        return $article_info[$key+1];
                    }
                }
            }
            return false;
        }
    }
    //无匹配回复
    public function getAutoReply(){
        if($replyRow = D("AutoReply")->where(array('type'=>'2','state'=>'1'))->find()){
            return $this->create_xmlcontent('text', $replyRow['content']);
        }else{
            return false;
        }
    }
    
    //收到的消息入库
    protected function addMessage() {
        if($this->post_data['Keyword'] != ''){
            $row = array();
            $row['customer_id'] = $this->customer_id;
            $row['fromuser']    = $this->post_data['FromUserName'];
            $row['touser']      = $this->post_data['ToUserName'];
            $row['msgtype']     = $this->post_data['FromMsgType'];
            $row['msg_content'] = $this->post_data['Keyword'];
            $row['create_time'] = $this->post_data['CreateTime'];
            D('Message')->add($row);
        }
    }
    
    //文字回复
    public function getText($id='',$content = ''){
        if(empty($content)){
        	$WxCommon = D('Common');
        	$inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        	$WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        	return array('msgtype'=>'text','content'=>$inforesult['content']);
        }else{
        	return array('msgtype'=>'text','content'=>$content);
        }
    }
    //图片回复
    public function getImage($id){
    	$WxCommon = D('Common');
    	$inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        // file_put_contents('aaa.txt',$inforesult,FILE_APPEND);
    	$WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
    	if(empty($inforesult['pic'])){
    		return false;
    	}else{
    		//上传图片
    		$token = D('Customer')->getToken($this->customer_id);
    		$result = D('Api')->upTempImage($token,$_SERVER['DOCUMENT_ROOT'].$inforesult['pic']);
            $result = json_decode($result,true);
    		if(!empty($result['media_id'])){
    			$data['msgtype'] = 'image';
    			$data['bodystr'] = "
	    			<MsgType><![CDATA[image]]></MsgType>
	    			<Image>
	    			<MediaId><![CDATA[{$result['media_id']}]]></MediaId>
	    			</Image>";
    			return $data;
    		}else{
    			return false;
    		}
    	}
    }
    //单图文回复
    public function getSingle($id){
        $WxCommon = D('Common');
        $inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        
        $data['msgtype']     = 'news';
        $data['title']       = $inforesult['title'];
        $data['description'] = $inforesult['des'] ? $inforesult['des'] : cut_str(delete_html($data['content']), 80);
        $data['picurl']      = C('PRO_URL').trim($inforesult['pic'],'.');
        $data['url']         = $inforesult['url'];
        if(empty($data['url']))
            $data['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Home/WxArticle/single',array('id'=>$id));
        
        return $data;
    }
    //多图文回复
    public function getMuti($id,$datas = array()){
    	if(empty($datas)){
            $WxCommon = D('Common');
            $result = $WxCommon->where(array('id'=>$id,'state'=>'1'))->select();
    		$WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
    		$commonDetail = D('CommonDetail');
    		$datas = $commonDetail->where(array('common_id'=>$id))->order("order_num asc")->select();
    	}
        $i = 0;
        $itemlist = '';
        $infocount = count($datas);
        
        for($i=0; $i < $infocount; $i++){
            if(!$datas[$i]['url']){
                $url = 'http://'.$_SERVER['HTTP_HOST'] .U('Home/WxArticle/muti',array('id'=>$datas[$i]['id']));
            }else{
                $url = $datas[$i]['url'];
            }
            $datas[$i]['description'] = cut_str(trim(strip_tags(html_entity_decode($datas[$i]['content']))),60);
            $itemlist .= "<item>
                 <Title><![CDATA[{$datas[$i]['title']}]]></Title>
                 <Description><![CDATA[{$datas[$i]['description']}]]></Description>
                 <PicUrl><![CDATA[http://{$_SERVER['HTTP_HOST']}{$datas[$i]['pic']}]]></PicUrl>
                 <Url><![CDATA[$url]]></Url>
            </item>";
        }
    	if ($i > 0) {
    		$Bodystr = "
    		<ArticleCount>$infocount</ArticleCount>
    		<Articles>
    		$itemlist
    		</Articles>";
    		$data['msgtype']	= 'news';
    		$data['bodystr']	= $Bodystr;
    		return $data;
    	}
    	return false;
    }
    //获取最近的5个网点信息组成多图文
    public function getWebsiteInfo(){
        $Website = D('Website');
        $where = array();
        $where['customer_id'] = $this->customer_id;
        $where['status'] = '1';
        $where['dele_status'] = '1';
        $lng = $this->post_data['Location_Y'];
		$lat = $this->post_data['Location_X'];
        $order = 'distance asc,add_time desc';
		$Website->field('*,ACOS(SIN((' . $lat . ' * '.M_PI.') / 180) * SIN((lat * '.M_PI.') / 180 ) +COS((' . $lat . ' * '.M_PI.') / 180 ) * COS((lat * '.M_PI.') / 180 ) *COS((' . $lng . '* '.M_PI.') / 180 - (lng * '.M_PI.') / 180 ) ) * 6371 as distance');
        $info = $Website->where($where)->order($order)->limit(5)->select();
        $datas = array();

        foreach($info as $key=>$val){
            if($val['distance']>=1){
				$datas[$key]['title'] = $val['name'].' : '.round($val['distance'],1).'km';
			}else{
				$datas[$key]['title'] = $val['name'].' : '.(round($val['distance'],3)*1000).'m';
			}
            $datas[$key]['content'] = $val['profile'];
            $datas[$key]['pic'] = $val['pic'];
            $datas[$key]['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Website/index',array('id'=>$val['id']));
        	$Website->where(array('id'=>$val['id']))->setInc('push_num');//网点推送次数加一
        }
    	return $this->getMuti('',$datas);
    }
    /**
     * 组合xml内容 
     * @param string $msgtype text文字,news图文,music音乐
     * @param string $content 文字消息体
     * @param string $title 图文标题
     * @param string $description 图文简介
     * @param string $picurl 图文封面
     * @param string $url 图文链接
     * @param string $bodystr 已组合好的格式体，通常用在多图文中
     */
    public function create_xmlcontent($msgtype, $content='', $title='', $description='', $picurl='', $url='', $bodystr=''){
        if($msgtype == 'text'){
            $content = str_replace("\r","",$content);
            $bodystr = '<Content><![CDATA['.$content.']]></Content>';
        }elseif($msgtype == 'news'){
            if ($bodystr == ''){
                $description = cut_str($description, 120);
                $bodystr = "<ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[$title]]></Title>
                    <Description><![CDATA[$description]]></Description>
                    <PicUrl><![CDATA[$picurl]]></PicUrl>
                    <Url><![CDATA[$url]]></Url>
                    </item>
                    </Articles>";
            }
        }elseif($msgtype == 'music'){
            $bodystr = "<Music>
                <Title><![CDATA[$title]]></Title>
                <Description><![CDATA[$description]]></Description>
                <MusicUrl><![CDATA[$url]]></MusicUrl>
                <HQMusicUrl><![CDATA[$url]]></HQMusicUrl>
                </Music>";
        }
        
        $xmlcontent = "<xml>
            <ToUserName><![CDATA[".$this->post_data['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[" . $this->post_data['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[".$msgtype."]]></MsgType>
            ".$bodystr."
            <FuncFlag>0</FuncFlag>
            </xml>";
        return $xmlcontent;
    }
    
    //公众平台校验
    private function valid($token){
        $echoStr   = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];
        // file_put_contents('aaa.txt',json_encode($_REQUEST));
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature) return $echoStr;
    }
}
